#!/bin/bash

include "log.sh"

ADBDevice=""
ADB="adb"
function adb::set_device()
{
    ADBDevice="$1"
    if [ "$ADBDevice" != "" ]; then
        ADB="adb -s $ADBDevice"
    else
        ADB="adb"
    fi
    flogd "set to $1"
}

function adb::shell()
{
    $ADB shell $*
}

function adb::input()
{
    flogd "adb::input: $*"
    adb::shell input $*
    luwh::assert $? == 0 "exec $* failed"
}

function adb::input::motion()
{
    adb::input motionevent $*
}

function adb::input::click()
{
    adb::input tap $*
}

function adb::input::key()
{
    adb::input keyevent KEYCODE_$1
}

function adb::screen::is_awake()
{
    result=$(adb::shell dumpsys window policy | grep interactiveState)
    luwh::assert $result != "" "window policy don't have interactiveState"
    # interactiveState=INTERACTIVE_STATE_SLEEP
    # interactiveState=INTERACTIVE_STATE_AWAKE
    eval "$result"
    [ "$interactiveState" == "INTERACTIVE_STATE_AWAKE" ]
}

ADBCapFile="/tmp/screencap.png"
function adb::screen::set_cap_file()
{
    ADBCapFile="$1"
    flogd "set to $1"
}

function adb::screen::get_cap_file()
{
    echo $ADBCapFile
}

function adb::screen::cap()
{
    flogd "start cap to $ADBCapFile"
    rm -f $ADBCapFile

    while ! [ -e $ADBCapFile ]; do
        adb::shell screencap -p /sdcard/screencap.png
        $ADB pull /sdcard/screencap.png "$ADBCapFile"
    done
    flogd "end"
}

ADBRecordFile="screenrecord.mp4"
function adb::screen::set_record_file()
{
    ADBRecordFile="$1"
    flogd "set to $1"
}

ADBRecordTime="60"
function adb::screen::set_record_time()
{
    ADBRecordTime="$1"
    flogd "set to $1"
}

function adb::screen::record()
{
    flogd "start time: $ADBRecordTime, record to $ADBRecordFile"
    adb::shell screenrecord --time-limit "$ADBRecordTime" "/sdcard/$ADBRecordFile"
    flogd "end"
}
